$(function () {
  function fnSkrolTo($el) {
    let sthTop = $el.offset().top,
      skrolTop = $(window).scrollTop();
    if (skrolTop < sthTop) {
      $("html,body").animate(
        {
          minHeight: $(window).height() + sthTop,
          scrollTop: sthTop,
        },
        500
      );
    }
  }
  function fnGetOffsetBot($el) {
    return $el.offset().top + $el.outerHeight();
  }
  //--------------
  if (location.hash !== "") {
    $(".tab-content.default-tab").hide();
    $(".content-box-tabs .current").removeClass("current");
    $(location.hash).show();
    $('a[href="' + location.hash + '"]').addClass("current");
  }
  $(".content-box-tabs a").click(function () {
    //alert(this.href);
    window.history.pushState(null, null, this.href.replace(/#tab1/, ""));
  });
  $("#update").click(function () {
    $(this).val("提交中");
    fnSave((e) => {
      location.reload();
    });
    return false;
  });
  $(".ui-sortable input,#search-inp")
    .dblclick(function () {
      $(this).select();
    })
    .mouseenter(function () {
      $(this).focus();
    });
  $("#search-box").draggable({
    cancel: "select,button,a,input,p",
    cursor: "move",
  });
  $("#tab2 tbody").sortable({
    items: "tr",
    axis: "y",
    cursor: "move",
    cancel: "a,input",
    delay: 179,
    stop: function (event, ui) {
      window.setTimeout(fnSave, 879);
    },
  });
  $("#search-fill").click(function () {
    let $el = $(".js-tr" + $("#fill-id").val());
    if (objPub.info) {
      let objInfo = objPub.info;
      for (let i in objInfo) {
        $el.find("." + i).val(objInfo[i]);
      }
    }
  });
  $("a.js-fill").click(function () {
    $("#fill-id").val($(this).data("id"));
    fnSkrolTo($(".divHeader"));
    let $el = $(".js-tr" + $(this).data("id"));
    let opt = {
      top: $el.offset().top + $el.outerHeight() * 2.7,
      // left: $(".tdEdit").offset().left + $(".tdEdit").outerWidth()
      mid: $(".tdEdit").offset().left + $(".tdEdit").outerWidth(),
    };
    let limtTop = fnGetOffsetBot($("#tab2 tbody"));
    opt.top = opt.top > limtTop ? limtTop + (opt.top - limtTop) / 3 : opt.top;
    fnShowBox($("#search-box"), 0, opt);
    return false;
  });
  $("#search-btn").click(fnSearch);
  $("#search-box").dblclick(function (e) {
    fnShowBox($("#search-box"), e.target.nodeName === "DIV");
  });
  let objPub = {};

  function fnSearch() {
    let sWord = $("#search-inp").val();
    $("#search-result")
      .empty()
      .append("<option value='查询中'>查询中……</option>");
    fnAjax(sWord, function (data) {
      // console.log(data);
      $("#search-result").empty();
      for (let i in data) {
        let obj = data[i];
        $("<option value='" + obj.ID + "'>" + obj.Title + "</option>")
          .appendTo("#search-result")
          .click(function () {
            $("#search-result").val(obj.ID);
            $("#search-view").html(
              [obj.Title, obj.Url, obj.Img].map((a) => "<p>" + a + "</p>")
            );
            fnShowBox($("#search-box"), 0);
            $("#search-fill").removeAttr("disabled");
            objPub.info = obj;
          });
        // $("#search-result").append("<option value='Value'>" + obj.Title + "</option>");
      }
    });
  }

  function fnGenPostData(elId) {
    const data = [];
    $(`#${elId} tbody tr`).each(function () {
      const arrWEV = {};
      $(this)
        .find("input")
        .each(function () {
          // arrWEV.push($(this).val());
          arrWEV[$(this).attr("name")] = $(this).val();
        });
      data.push(arrWEV);
    });
    return data;
  }

  function fnSave(
    fnback = function (n) {
      console.log(n);
    }
  ) {
    const arrRTB = { slides: [], labels: [] };
    for (const key in arrRTB) {
      if (Object.hasOwnProperty.call(arrRTB, key)) {
        arrRTB[key] = fnGenPostData(key);
      }
    }
    console.log(arrRTB);
    // return false;
    $.post(
      "main.php?act=update",
      {
        data: JSON.stringify(arrRTB),
      },
      function (data) {
        fnback(data);
        //alert("Data Loaded: " + data);
      }
    );
  }

  function fnShowBox($el, hide = 0, opt = {}) {
    if ($el.is(":hidden") || Object.keys(opt).length) {
      // let minWidth = parseInt($el.css("minWidth")),
      //   top = parseInt($el.css("top"));
      opt.top =
        opt.top ||
        ($(window).height() - $el.outerHeight()) / 2 +
          $(window).scrollTop() -
          37;
      opt.left = opt.left || ($(window).width() - $el.outerWidth()) / 2;
      opt.left = opt.mid - $el.outerWidth() / 2 || opt.left;
      $el.fadeIn().animate({
        top: opt.top,
        left: opt.left,
        minWidth: $el.outerWidth(),
        opacity: 1,
      });
    } else if (!hide) {
      $el.animate({
        minWidth: $el.outerWidth(),
      });
    } else {
      $el.fadeOut();
    }
  }

  function fnAjax(
    q,
    fnback = function (n) {
      console.log(n);
    }
  ) {
    let objRlt;
    $.getJSON(ajaxurl + "acgME&q=" + q, function (data) {
      if (data) {
        objRlt = data;
        fnback(objRlt.data);
      }
    });
  }

  function fnSelct(el) {
    var b = document;
    if (b.body.createTextRange) {
      var d = b.body.createTextRange();
      d.moveToElementText(el), d.select();
    } else if (window.getSelection) {
      var e = window.getSelection(),
        d = b.createRange();
      d.selectNodeContents(el), e.removeAllRanges(), e.addRange(d);
    }
  }
  $("#search-view").on("mouseenter", "p", function (c) {
    let d = $(this).html();
    $(this).click(function () {
      fnSelct($(this)[0]);
    });
    fnSelct($(this)[0]);
    $(this).on("mouseleave", function (c) {
      $(this).html(d);
    });
  });
});
